<template>
  <PageWrapper>
    <view class="flex flex-col gap-24rpx justify-center items-center p-48rpx">
      <image :src="avatarUrl" class="w-300rpx h-300rpx rounded-full" />
      <view class="w-full">
        <wd-button block @click="chooseImage">上传头像</wd-button>
      </view>
    </view>
    <wd-img-cropper v-model="show" :img-src="src" @confirm="handleConfirm" @cancel="handleCancel" />
  </PageWrapper>
</template>
<script setup lang="ts">
  import PageWrapper from '@/components/Page/PageWrapper.vue';
  import { useUserStore } from '@/store/modules/user';
  import { computed, ref } from 'vue';
  import { userUpdateAvatar } from '@/api/system/profile';

  const userStore = useUserStore();
  const avatarUrl = computed(() => userStore.userInfo?.avatar ?? '');

  const show = ref(false);
  const src = ref('');

  function chooseImage() {
    uni.chooseImage({
      count: 1,
      success: (res) => {
        const tempFilePaths = res.tempFilePaths[0];
        src.value = tempFilePaths;
        show.value = true;
      },
    });
  }

  /**
   *
   * @param tempFilePath h5拿到的是base64字符串 小程序拿到的是链接
   */
  async function handleConfirm(e: { tempFilePath: string }) {
    console.log(e);
    const base64Str = e.tempFilePath;
    await userUpdateAvatar(base64Str);
    // 更新
    await userStore.loadUserInfo(false);
    uni.showModal({ title: '提示', content: '上传成功', showCancel: false });
  }

  function handleCancel() {
    show.value = false;
  }
</script>

<style scoped></style>
